package com.doangeometrydash.player;

import org.andengine.engine.camera.BoundCamera;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.doangeometrydash.manager.ResourcesManager;

public class Player
{

	private Body body;
	private boolean allowJump;
	private Sprite player;
	private boolean canMove;
	private float vx;
	private float vy;

	public Player(float pX, float pY, float vX, float vY, VertexBufferObjectManager vbom, final BoundCamera camera, PhysicsWorld physicsWorld, Scene scene)
	{
		player = new Sprite(pX, pY, ResourcesManager.getInstance().player_region, vbom);
		canMove = false;
		scene.attachChild(player);
		body = PhysicsFactory.createBoxBody(physicsWorld, player, BodyType.DynamicBody, PhysicsFactory.createFixtureDef(0, 0, 0));
		body.setUserData("player");

		vx = vX;
		vy = vY;
		update(camera, physicsWorld);
		camera.setChaseEntity(player);		
	}

	private void update(final BoundCamera camera, PhysicsWorld physicsWorld)
	{
		physicsWorld.registerPhysicsConnector(new PhysicsConnector(player, body, true, true)
		{
			@Override
			public void onUpdate(float pSecondsElapsed)
			{
				super.onUpdate(pSecondsElapsed);
				camera.onUpdate(0.1f);
				if (canMove)
				{
					body.setLinearVelocity(new Vector2(vx, body.getLinearVelocity().y));
				}
			}
		});
	}

	public void jump()
	{
		if (allowJump)
		{
			body.setLinearVelocity(new Vector2(body.getLinearVelocity().x, vy));
		}
	}

	public void setAllowJump(boolean a)
	{
		allowJump = a;
	}

	public Body getPlayerBody()
	{
		return body;
	}

	public void setAllowRun(boolean b)
	{
		canMove = b;
	}
	
	public void setVelocity(float vX, float vY)
	{
		vx = vX;
		vy = vY;
	}
}
